# -*- coding: utf-8 -*-
from django import template
from django import forms
from django.http import HttpResponse, Http404,HttpResponseRedirect
from django.shortcuts import render, render_to_response
from django.template import Context, loader
from django.views.generic import View, TemplateView, ListView, DetailView
from django.db.models import Q
from django.core.cache import caches



from Blog.models import *
# from vmaig_comments.models import Comment
# from vmaig_auth.models import VmaigUser
# from vmaig_system.models import Link
# from vmaig_auth.forms import VmaigUserCreationForm, VmaigPasswordRestForm
from django.conf import settings
import datetime
import time
import json
import logging
from django.contrib.sessions.models import Session


PAGE_NUM=5
class Link:
    def __init__(self,title,url,type,create_time='',update_time=''):
        self.title=title
        self.url=url
        self.type=type
        self.create_time=create_time
        self.update_time=update_time

def links():
    data=[]
    data.append(Link("教务处","http://jwc.ecust.edu.cn","123",'',''))
    data.append(Link("教务处2","http://jwc.ecust.edu.cn","123",'',''))
    return data

class Nav:
    def __init__(self,name,url,status=1,create_time='',):
        self.name=name
        self.url=url
        self.status=status
        self.status=status
        self.create_time=create_time

def navs():
    data=[]
    data.append(Nav("C教程","/blog/category/C教程/"))
    data.append(Nav("C案例","/blog/category/C案例/"))
    data.append(Nav("Python教程","/blog/category/Python教程/"))
    data.append(Nav("Python案例","/blog/category/Python案例/"))
    data.append(Nav("切换论坛","/blog/column.html"))
    data.append(Nav("返回主页","/"))
    return data

class Carousel:
    def __init__(self,title,summary,url,img='/static/img/carousel/bigdata2.jpg'):
        self.title=title
        self.summary=summary
        self.img=img
        self.url=url
def carousels():
    data=[]
    data.append(Carousel("DataAnalysis","@2017","http://sjfx.piclass.cn"))
    data.append(Carousel("DataAnalysis","@2017","http://sjfx.piclass.cn"))
    data.append(Carousel("DataAnalysis","@2017","http://sjfx.piclass.cn"))
    return data
        


# 缓存
try:
    cache = caches['memcache']
except ImportError as e:
    cache = caches['default']

# logger
# logger = logging.getLogger(__name__)
WEBSITE_TITLE="数据分析"
WEBSITE_WELCOME="Welcome to our blog!"



class BaseMixin(object):
    def get_context_data(self, *args, **kwargs):
        context = super(BaseMixin, self).get_context_data(**kwargs)
        
            # 网站标题等内容
        context['website_title'] = WEBSITE_TITLE
        context['website_welcome'] = WEBSITE_WELCOME
        # 热门文章
        context['hot_article_list'] = \
            Article.objects.filter(Q(status=0) &Q(column=self.request.session["column"])).order_by("-view_times")[0:10]
        
        # 导航条
        context['nav_list'] = navs()
        # 最新评论
        context['latest_comment_list'] = \
            Comment.objects.order_by("-create_time")[0:10]
        # 友情链接
        context['links'] = links()
        colors = ['primary', 'success', 'info', 'warning', 'danger']
        for index, link in enumerate(context['links']):
            link.color = colors[index % len(colors)]

        username=self.request.session["username"]
        context['notification_count']=Notification.objects.filter(Q(to_user=username)&Q(is_read=0)).count()

        context["column"]=Column.objects.get(id=self.request.session["column"])

        

        #用户未读消息数
        

        

        return context


class IndexView(BaseMixin, ListView):
    template_name = 'blog/index.html'
    context_object_name = 'article_list'
    paginate_by = PAGE_NUM  # 分页--每页的数目
    
    


    def get_context_data(self, **kwargs):
        # 轮播

        kwargs['carousel_page_list'] =carousels()
        
        return super(IndexView, self).get_context_data(**kwargs)

    def get_queryset(self):
        self.request.session["column"]=self.request.GET.get("column",1)
        article_list = Article.objects.filter(Q(status=0)&Q(column=self.request.session["column"]))
        return article_list


class ArticleView(BaseMixin, DetailView):
    template_name = 'blog/article.html'
    
    context_object_name = 'article'
    slug_field = 'id'
    queryset=None


    def get(self, request, *args, **kwargs):
        column=Column.objects.get(id=request.session["column"])
        if column.zy_id:
            self.template_name ='blog/PDFarticle.html'

        self.queryset = Article.objects.filter(Q(status=0) ,
            column=self.request.session["column"])

        # 统计文章的访问访问次数
        if 'HTTP_X_FORWARDED_FOR' in request.META:
            ip = request.META['HTTP_X_FORWARDED_FOR']
        else:
            ip = request.META['REMOTE_ADDR']
        self.cur_user_ip = ip

        id = self.kwargs.get('slug')
        print "id",id
        # 获取15*60s时间内访问过这篇文章的所有ip
        visited_ips = cache.get(id, [])

        # 如果ip不存在就把文章的浏览次数+1
        if ip not in visited_ips:
            try:
                article = self.queryset.get(id=id)
            except Article.DoesNotExist:
                logger.error(u'[ArticleView]访问不存在的文章:[%s]' % id)
                raise Http404
            else:
                article.view_times += 1
                article.save()
                visited_ips.append(ip)

            # 更新缓存
            cache.set(id, visited_ips, 15*60)

        return super(ArticleView, self).get(request, *args, **kwargs)

    def get_context_data(self, **kwargs):
        self.queryset = Article.objects.filter(Q(status=0) ,column=self.request.session["column"])

        # 评论
        id = self.kwargs.get('slug', '')
        kwargs['comment_list'] = \
            self.queryset.get(id=id).comment_set.all()

        

        
        column=Column.objects.get(id=self.request.session["column"])
        if column.zy_id:

            zy=ZyDetail.objects.get(id=column.zy_id)
            
            column.zy_id2=zy.zy_id.id

            kwargs["column"]=column
            kwargs["zy_id"]=zy.zy_id.id


            kwargs["peer_response_list"]=BlogScore.objects.filter(article_id=id)

            
        else:
            kwargs['comment_list'] = \
            self.queryset.get(id=id).comment_set.all()


        return super(ArticleView, self).get_context_data(**kwargs)


class AllView(BaseMixin, ListView):
    template_name = 'blog/all.html'
    context_object_name = 'article_list'

    def get_context_data(self, **kwargs):
        kwargs['category_list'] = set(Article.objects.only('category').filter(Q(status=0) &Q(column=self.request.session["column"])).values_list('category', flat=True))

        kwargs['PAGE_NUM'] = PAGE_NUM
        return super(AllView, self).get_context_data(**kwargs)

    def get_queryset(self):
        article_list = Article.objects.filter(Q(status=0) &Q(column=self.request.session["column"])).order_by("-pub_time")[0:PAGE_NUM]
        return article_list

    def post(self, request, *args, **kwargs):
        val = self.request.POST.get("val", "")
        sort = self.request.POST.get("sort", "time")
        start = self.request.POST.get("start", 0)
        end = self.request.POST.get("end", PAGE_NUM)

        start = int(start)
        end = int(end)

        if sort == "time":
            sort = "-pub_time"
        elif sort == "recommend":
            sort = "-view_times"
        else:
            sort = "-pub_time"

        if val == "all":
            article_list = \
                Article.objects.filter(Q(status=0) &Q(column=self.request.session["column"])).order_by(sort)[start:end+1]
        else:
            try:
                article_list = Article.objects.filter(Q(status=0)&Q(category=val)&Q(column=self.request.session["column"])).order_by(sort)[start:end+1]
            except :
                logger.error(u'[AllView]此分类不存在:[%s]' % val)
                raise PermissionDenied

        isend = len(article_list) != (end-start+1)

        article_list = article_list[0:end-start]

        html = ""
        for article in article_list:
            html += template.loader.get_template(
                        'blog/include/all_post.html'
                    ).render(template.Context({'post': article}))

        mydict = {"html": html, "isend": isend}
        return HttpResponse(
            json.dumps(mydict),
            content_type="application/json"
        )


class SearchView(BaseMixin, ListView):
    template_name = 'blog/search.html'
    context_object_name = 'article_list'
    paginate_by = PAGE_NUM

    def get_context_data(self, **kwargs):
        kwargs['s'] = self.request.GET.get('s', '')
        return super(SearchView, self).get_context_data(**kwargs)

    def get_queryset(self):
        # 获取搜索的关键字
        s = self.request.GET.get('s', '')
        # 在文章的标题,summary和tags中搜索关键字
        article_list = Article.objects.only(
            'title', 'summary', 'tags'
        ).filter(
            Q(title__icontains=s) |
            Q(summary__icontains=s) |
            
            Q(tags__icontains=s),
            status=0,
            column=self.request.session["column"]
        )
        return article_list


class TagView(BaseMixin, ListView):
    template_name = 'blog/tag.html'
    context_object_name = 'article_list'
    paginate_by = PAGE_NUM

    def get_queryset(self):
        tag = self.kwargs.get('tag', '')
        article_list = \
            Article.objects.filter(tags__icontains=tag, status=0,
            column=self.request.session["column"])

        return article_list


class CategoryView(BaseMixin, ListView):
    template_name = 'blog/category.html'
    context_object_name = 'article_list'
    paginate_by = PAGE_NUM

    def get_queryset(self):
        self.request.session["column"]=1 # test
        category = self.kwargs.get('category', '')
        try:
            # article_list = \
            #     Category.objects.get(name=category).article_set.all()
            # article_list=Article.objects.only('category').filter(category=category)
            article_list=Article.objects.filter(category=category,
            column=self.request.session["column"])

        except Category.DoesNotExist:
            logger.error(u'[CategoryView]此分类不存在:[%s]' % category)
            raise Http404

        return article_list





class NewsView(BaseMixin, TemplateView):
    template_name = 'blog/news.html'

    def get_context_data(self, **kwargs):
        timeblocks = []

        # 获取开始和终止的日期
        start_day = self.request.GET.get("start", "0")
        end_day = self.request.GET.get("end", "6")
        start_day = int(start_day)
        end_day = int(end_day)

        start_date = datetime.datetime.now()

        # 获取url中时间断的资讯
        for x in range(start_day, end_day+1):
            date = start_date - datetime.timedelta(x)
            news_list = News.objects.filter(
                pub_time__year=date.year,
                pub_time__month=date.month,
                pub_time__day=date.day
            )

            if news_list:
                timeblocks.append(news_list)

        kwargs['timeblocks'] = timeblocks
        kwargs['active'] = start_day/7  # li中那个显示active

        return super(NewsView, self).get_context_data(**kwargs)

ArticleModel = Article


# Create your views here.

class CommentControl(View):
    def post(self, request, *args, **kwargs):
        # 获取当前用户
        user = User.objects.get(username=request.session["username"])
        # 获取评论
        text = self.request.POST.get("comment", "")
        # 判断当前用户是否是活动的用户
        
        id = self.kwargs.get('slug', '')
        try:
            # 默认使用pk来索引(也可根据需要使用title,id在索引
            article = ArticleModel.objects.get(id=id)
        except ArticleModel.DoesNotExist:
            logger.error(u'[CommentControl]此文章不存在:[%s]' % id)
            raise PermissionDenied

        # 保存评论
        parent = None
        if text.startswith('@['):
            import ast
            parent_str = text[1:text.find(':')]
            parent_id = ast.literal_eval(parent_str)[1]
            text = text[text.find(':')+2:]

            try:
                parent = Comment.objects.get(pk=parent_id)
                info = u'{}回复了你在 {} 的评论'.format(
                    user.username,
                    parent.article.title
                )
                Notification.objects.create(
                    title=info,
                    text=text,
                    from_user=user,
                    to_user=parent.username,
                    url='/article/'+id+'.html'
                )
            except Comment.DoesNotExist:
                #logger.error(u'[CommentControl]评论引用错误:%s' % parent_str)
                return HttpResponse(u"请勿修改评论代码！", status=403)

        if not text:
            # logger.error(
            #     u'[CommentControl]当前用户输入空评论:[{}]'.format(
            #         user.username
            #     )
            # )
            return HttpResponse(u"请输入评论内容！", status=403)

        comment = Comment.objects.create(
                username=user,
                article=article,
                text=text,
                parent=parent
                )

        
        img = "http://vmaig.qiniudn.com/image/tx/tx-default.jpg"

        print_comment = u"<p>评论：{}</p>".format(text)
        if parent:
            print_comment = u"<div class=\"comment-quote\">\
                                  <p>\
                                      <a>@{}</a>\
                                      {}\
                                  </p>\
                              </div>".format(
                                  parent.username.username,
                                  parent.text
                              ) + print_comment
        # 返回当前评论
        html = u"<li>\
                    <div class=\"vmaig-comment-tx\">\
                        <img src={} width=\"40\"></img>\
                    </div>\
                    <div class=\"vmaig-comment-content\">\
                        <a><h1>{}</h1></a>\
                        {}\
                        <p>{}</p>\
                    </div>\
                </li>".format(
                    img,
                    comment.username.username,
                    print_comment,
                    datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
                )

        return HttpResponse(html)


class UserView(BaseMixin, TemplateView):
    template_name = 'blog/user.html'

    def get(self, request, *args, **kwargs):
        slug = self.kwargs.get('slug')

        if slug == 'notification':
            self.template_name = 'blog/user_notification.html'

        return super(UserView, self).get(request, *args, **kwargs)

        logger.error(u'[UserView]不存在此接口')
        raise Http404

    def get_context_data(self, **kwargs):
        context = super(UserView, self).get_context_data(**kwargs)

        slug = self.kwargs.get('slug')

        if slug == 'notification':
            context['notifications'] = \
                Notification.objects.filter(to_user=self.request.session["username"]).order_by(
                    '-create_time'
                ).all()

        return context

class UserControl(View):

    def post(self, request, *args, **kwargs):
        # 获取要对用户进行什么操作
        slug = self.kwargs.get('slug')

        if  slug == "notification":
            return self.notification(request)

        raise PermissionDenied

    def notification(self, request):
        
        notification_id = self.request.POST.get("notification_id", "")
        notification_id = int(notification_id)

        notification = Notification.objects.filter(
            pk=notification_id
        ).first()

        if notification:
            notification.is_read = True
            notification.save()
            mydict = {"url": '/blog'+notification.url}
            print(mydict)
        else:
            mydict = {"url": '#'}

        return HttpResponse(
            json.dumps(mydict),
            content_type="application/json"
        )

class Publish(BaseMixin, TemplateView):
    template_name = 'blog/publish.html'
    

    def get_context_data(self, **kwargs):

        context = super(Publish, self).get_context_data(**kwargs)        
        return context

    def post(self,request, **kwargs):
        id=request.POST["id"]
        title=request.POST["title"]
        content=request.POST["content"]
        category=request.POST["category"]
        status=request.POST["status"]
        summary=request.POST["summary"]
        tags=request.POST["tags"]
        img=request.POST.get("img","/static/img/article/default.jpg")
        
        user=User.objects.get(username=request.session["username"])
        column=Column.objects.get(id=request.session["column"])

        if id=="":
            article=Article.objects.create(username=user,
                title=title,
                content=content,
                category=category,
                status=status,
                tags=tags,
                img=img,
                column=column,
                summary=summary,
                pub_time=time.strftime("%Y-%m-%d %H:%M:%S",time.localtime())
                )
            kwargs["notice"]="success"
            kwargs["tc"]=Article.objects.get(id=article.id)
            return super(Publish, self).get(request,**kwargs)
        else:
            article=Article.objects.get(id=id)

            
            article.title=title
            article.content=content
            article.category=category
            article.status=status
            article.tags=tags
            article.img=img
            article.column=column
            article.summary=summary
            article.pub_time=time.strftime("%Y-%m-%d %H:%M:%S",time.localtime())
            article.save()
            kwargs["notice"]="修改成功"
            kwargs["tc"]=Article.objects.get(id=article.id)
            return super(Publish, self).get(request,**kwargs) 

    def get(self,request,**kwargs):
        if request.GET.has_key("id"):
            kwargs["tc"]=Article.objects.get(id=request.GET["id"])
        else:
            kwargs["tc"]=None
        return super(Publish, self).get(request,**kwargs) 


class UserArticle(BaseMixin, TemplateView):
    template_name = 'blog/user_articles.html'

    def get_context_data(self, **kwargs):
        kwargs["article_list"]=self.get_queryset(self.request)

        context = super(UserArticle, self).get_context_data(**kwargs)        
        return context

    def get_queryset(self,request):
        
        article_list = Article.objects.filter(Q(column=request.session["column"])&Q(username=request.session["username"]))
        return article_list

    def post(self,request, **kwargs):
        Article.objects.get(Q(username=request.session["username"])&Q(id=request.POST["delete_id"])).delete()
        kwargs["article_list"]=self.get_queryset(self.request)
        return super(UserArticle, self).get(request,**kwargs)  


def  ColumnView(request):
    if request.method=="POST" and request.session["role"]!='2':
        id=request.POST["id"]
        class_id=",".join(request.POST.getlist("class"))
        name=request.POST["name"]
        summary=request.POST["summary"]
        if request.POST.has_key("delete"):
            Column.objects.get(id=id).delete()
        else:
            if id:
                column=Column.objects.get(id=id)
                column.class_id=class_id
                column.name=name
                column.summary=summary
                column.save()
            else:
                Column.objects.create(
                    username=User.objects.get(username=request.session["username"]),
                    class_id=class_id,
                    name=name,
                    summary=summary,

                    )
   


    if request.session["role"]=='2':
        column=[]
        myclass=Student.objects.filter(username=request.session["username"]).values_list('class_id', flat=True)
        myclass=set(myclass)
        data=Column.objects.all()
        for item in data:
            if set(item.class_id.split(","))&myclass or item.class_id=="":
                #print set(item.class_id.split(",")),myclass,item.zy_id
                column.append(item)

        
    else:
        myclass=Class.objects.filter(username=request.session["username"])
        column=Column.objects.filter( Q(username=request.session["username"]) | Q(class_id="") )
    

    return render(request,"blog/column.html",{'myclass':myclass,'column':column})


def PeerResponse(request):
    if request.method=="POST":
        if request.POST.has_key("submit"):
            article_id,zy_id=request.POST["article_id"],request.POST["zy_id"]
            comment,score=request.POST["comment"],request.POST["score"]

            article=Article.objects.get(id=article_id)
            zy=ZyDetail.objects.get(id=zy_id)

            user=User.objects.get(username=request.session["username"])
            if user.role!='2':
                flag=1
            else:
                flag=0

            data=BlogScore.objects.filter(username=request.session["username"],article_id=article_id)
            if data:
                data[0].comment=comment
                data[0].score=score
                data[0].save()
            else:
                BlogScore.objects.create(
                    username=user,
                    stu_id=article.username,
                    article_id=article_id,
                    score=score,
                    comment=comment,
                    zy=zy,
                    flag=flag,
            )
            return HttpResponseRedirect("/blog/article/%s.html"%article_id)


    return HttpResponse("/blog/article/%s.html"%article_id)







        
    
